package com.vibeplayer.app.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.vibeplayer.app.R;
import com.vibeplayer.app.activity.LyricEditorActivity;
import com.vibeplayer.app.adapter.LyricLineAdapter;
import com.vibeplayer.app.model.Song;
import com.vibeplayer.app.util.LrcParser;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class LyricPreviewFragment extends Fragment {

    private RecyclerView recyclerViewLyrics;
    private ImageButton btnPlay;
    private SeekBar seekBarPreview;
    private TextView txtTime;
    
    private LyricLineAdapter adapter;
    private LrcParser lrcParser;
    private Song currentSong;
    private Handler handler;
    private boolean isPlaying = false;
    private int currentPosition = 0;
    private int duration = 0;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_lyric_preview, container, false);
        
        recyclerViewLyrics = view.findViewById(R.id.recyclerViewLyrics);
        btnPlay = view.findViewById(R.id.btnPlay);
        seekBarPreview = view.findViewById(R.id.seekBarPreview);
        txtTime = view.findViewById(R.id.txtTime);
        
        // 初始化Handler
        handler = new Handler(Looper.getMainLooper());
        
        // 初始化歌词解析器
        lrcParser = new LrcParser();
        
        // 获取当前歌曲
        if (getActivity() instanceof LyricEditorActivity) {
            currentSong = ((LyricEditorActivity) getActivity()).getSong();
            if (currentSong != null) {
                duration = 180000; // 默认3分钟，实际应该从歌曲中获取
                seekBarPreview.setMax(duration);
                updateTimeText();
            }
        }
        
        // 设置RecyclerView
        recyclerViewLyrics.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new LyricLineAdapter(new ArrayList<>());
        recyclerViewLyrics.setAdapter(adapter);
        
        // 设置按钮点击事件
        btnPlay.setOnClickListener(v -> togglePlayback());
        
        // 设置SeekBar监听器
        seekBarPreview.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    currentPosition = progress;
                    updateTimeText();
                    highlightCurrentLyric();
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        
        // 加载歌词
        loadLyrics();
        
        return view;
    }
    
    @Override
    public void onResume() {
        super.onResume();
        loadLyrics(); // 在恢复时重新加载歌词，以便在编辑后看到更新
    }
    
    @Override
    public void onPause() {
        super.onPause();
        stopPlayback(); // 停止播放
    }
    
    /**
     * 加载歌词
     */
    private void loadLyrics() {
        if (currentSong == null) {
            return;
        }
        
        String songPath = currentSong.getPath();
        String lrcPath = songPath.substring(0, songPath.lastIndexOf(".")) + ".lrc";
        File lrcFile = new File(lrcPath);
        
        if (lrcFile.exists() && lrcParser.loadLrc(lrcFile)) {
            List<LrcParser.LrcEntry> entries = lrcParser.getLrcEntries();
            adapter.setLyricLines(entries);
            adapter.notifyDataSetChanged();
        }
    }
    
    /**
     * 切换播放状态
     */
    private void togglePlayback() {
        if (isPlaying) {
            stopPlayback();
        } else {
            startPlayback();
        }
    }
    
    /**
     * 开始播放
     */
    private void startPlayback() {
        isPlaying = true;
        btnPlay.setImageResource(R.drawable.ic_pause);
        
        // 开始模拟播放进度
        handler.post(playbackRunnable);
    }
    
    /**
     * 停止播放
     */
    private void stopPlayback() {
        isPlaying = false;
        btnPlay.setImageResource(R.drawable.ic_play);
        
        // 停止模拟播放进度
        handler.removeCallbacks(playbackRunnable);
    }
    
    /**
     * 更新时间文本
     */
    private void updateTimeText() {
        String currentTime = formatTime(currentPosition);
        String totalTime = formatTime(duration);
        txtTime.setText(currentTime + " / " + totalTime);
    }
    
    /**
     * 高亮当前歌词
     */
    private void highlightCurrentLyric() {
        if (lrcParser.isLoaded()) {
            int index = lrcParser.findLyricIndex(currentPosition);
            if (index >= 0) {
                adapter.setHighlightedPosition(index);
                adapter.notifyDataSetChanged();
                
                // 滚动到当前歌词位置
                recyclerViewLyrics.smoothScrollToPosition(index);
            }
        }
    }
    
    /**
     * 格式化时间
     * @param milliseconds 毫秒
     * @return 格式化的时间字符串
     */
    private String formatTime(int milliseconds) {
        int seconds = (milliseconds / 1000) % 60;
        int minutes = (milliseconds / (1000 * 60)) % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }
    
    /**
     * 模拟播放进度的Runnable
     */
    private Runnable playbackRunnable = new Runnable() {
        @Override
        public void run() {
            if (isPlaying) {
                currentPosition += 100; // 每100毫秒更新一次
                if (currentPosition > duration) {
                    currentPosition = 0;
                    stopPlayback();
                } else {
                    seekBarPreview.setProgress(currentPosition);
                    updateTimeText();
                    highlightCurrentLyric();
                    
                    // 继续更新
                    handler.postDelayed(this, 100);
                }
            }
        }
    };
} 